package com.glowdayz.glowmee;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glowdayz.common.XmlParser;
import com.glowdayz.model.FirstCategoryCMD;
import com.glowdayz.model.SecondCategoryCMD;

public class ListReview extends Fragment {
	
    FrameLayout flContainer;
    DrawerLayout dlDrawer, dlDrawerIndex;
    View drawerView;
	
    ExpandableListView productCategoryList = null;
	ExpandableListAdapter listAdapter = null;
	List<FirstCategoryCMD> listDataHeader;
	HashMap<FirstCategoryCMD, List<SecondCategoryCMD>> listDataChild;
	
	int paramFilter = 0, paramOrder = 0, paramGender = 0, paramRating = 0, paramAge = 0, paramSkin = 0;
	int paramIdSecond = 0;
	String paramSecondText = null;
	
	LinearLayout reviewWait = null;
	
	String url = null;
	
	boolean isCheck = false;
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        View nowView = inflater.inflate(R.layout.activity_list_review, container, false);
		
		TextView textTitle = (TextView) nowView.findViewById(R.id.textTitle);
		textTitle.setText("전체리뷰");
		
		flContainer = (FrameLayout) nowView.findViewById(R.id.fl_activity_main_container);
		dlDrawer = (DrawerLayout) nowView.findViewById(R.id.drawer_layout);
		drawerView = nowView.findViewById(R.id.drawer);
		
		dlDrawerIndex = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
		dlDrawerIndex.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
		
        productCategoryList = (ExpandableListView) nowView.findViewById(R.id.list_slidermenu);
        
        reviewWait = (LinearLayout) nowView.findViewById(R.id.reviewWait);
		
        ImageView backBt = (ImageView) nowView.findViewById(R.id.backBt);
        backBt.setImageResource(R.drawable.pick_menu);
        backBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		backBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				dlDrawer.openDrawer(drawerView);
			}
		});
		
		Button categoryBt = (Button) nowView.findViewById(R.id.categoryBt);
		categoryBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				dlDrawer.closeDrawers();
			}
		});
		
		ImageView slideImg = (ImageView) nowView.findViewById(R.id.slideImg);
		slideImg.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				dlDrawer.closeDrawers();
			}
		});
		
		ImageView okBt = (ImageView) nowView.findViewById(R.id.okBt);
		okBt.setImageResource(R.drawable.pick_search);
		okBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		okBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(), ReviewFilter.class);
				intent.putExtra("PARAM_idSecond", paramIdSecond);
				intent.putExtra("PARAM_order", paramOrder);
				intent.putExtra("PARAM_gender", paramGender);
				intent.putExtra("PARAM_rating", paramRating);
				intent.putExtra("PARAM_age", paramAge);
				intent.putExtra("PARAM_skin", paramSkin);
				
				startActivityForResult(intent, 1);
			}
		});
        
		listDataHeader = new ArrayList<FirstCategoryCMD>();
		listDataChild = new HashMap<FirstCategoryCMD, List<SecondCategoryCMD>>();
		
		url = getResources().getString(R.string.server_url) + "/glowmee/categoryProductXml.do?type=2";
		
		(new CategoryWorker()).execute();
		
		productCategoryList.setDividerHeight(2);
		productCategoryList.setGroupIndicator(null);
		productCategoryList.setClickable(true);
        
        // Listview Group click listener
		productCategoryList.setOnGroupClickListener(new OnGroupClickListener() {
 			@Override
 			public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
 				 //Toast.makeText(getActivity(), listDataHeader.get(groupPosition).getFirstCategoryText(), Toast.LENGTH_SHORT).show();
 				return false;
 			} 
 		});
 		// Listview Group expanded listener
		productCategoryList.setOnGroupExpandListener(new OnGroupExpandListener() {
 			@Override
 			public void onGroupExpand(int groupPosition) {
 				//Toast.makeText(getActivity(), listDataHeader.get(groupPosition).getFirstCategoryText(), Toast.LENGTH_SHORT).show();
 			}
 		});
 		// Listview Group collasped listener
		productCategoryList.setOnGroupCollapseListener(new OnGroupCollapseListener() {
 		@Override
 			public void onGroupCollapse(int groupPosition) {
 				//Toast.makeText(getActivity(), listDataHeader.get(groupPosition).getFirstCategoryText(), Toast.LENGTH_SHORT).show();

 			}
 		});
 		// Listview on child click listener
		productCategoryList.setOnChildClickListener(new OnChildClickListener() {

 			@Override
 			public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
 				
 				ArrayList<SecondCategoryCMD> list = listDataHeader.get(groupPosition).getSecond_list();
 				SecondCategoryCMD item = list.get(childPosition);
 				dlDrawer.closeDrawers();
 				paramIdSecond = item.getIdSecondCategory();
 				paramSecondText = item.getSecondCategoryText();
 				isCheck = true;
 	            fragmentReplace(item.getIdSecondCategory());
 	            Index.isListReview = true;
 	            
 				return false;
 			}
 		});
        
		fragmentReplace(0);
		
		return nowView;
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			paramFilter = data.getIntExtra("PARAM_filter", 0);
			paramOrder = data.getIntExtra("PARAM_order", 0);
			paramGender = data.getIntExtra("PARAM_gender", 0);
			paramRating = data.getIntExtra("PARAM_rating", 0);
			paramAge = data.getIntExtra("PARAM_age", 0);
			paramSkin = data.getIntExtra("PARAM_skin", 0);
			paramIdSecond = data.getIntExtra("PARAM_idSecond", 0);
			isCheck = false;
			fragmentReplace(0);
		}
	}
	
	public void fragmentReplace(int reqNewFragmentIndex) {
		Bundle bundle = new Bundle();
		
		if (isCheck) {
			paramFilter = 0;
			paramOrder = 0;
			paramGender = 0;
			paramRating = 0;
			paramAge = 0;
			paramSkin = 0;
		}
		
		bundle.putInt("PARAM_idSecondCategory", reqNewFragmentIndex);
		bundle.putInt("PARAM_filter", paramFilter);
		bundle.putInt("PARAM_order", paramOrder);
		bundle.putInt("PARAM_gender", paramGender);
		bundle.putInt("PARAM_rating", paramRating);
		bundle.putInt("PARAM_age", paramAge);
		bundle.putInt("PARAM_skin", paramSkin);
		bundle.putInt("PARAM_idSecond", paramIdSecond);
		bundle.putString("PARAM_secondText", paramSecondText);
        Fragment newFragment = new ReviewFm();
        newFragment.setArguments(bundle);
        final FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.ll_fragment, newFragment);
        transaction.commit();
    }
	
	public class ExpandableListAdapter extends BaseExpandableListAdapter {

		private Context context;
		private List<FirstCategoryCMD> listDataHeader; // header titles
		// child data in format of header title, child title
		private HashMap<FirstCategoryCMD, List<SecondCategoryCMD>> listDataChild;
		public ExpandableListAdapter(Context context, List<FirstCategoryCMD> listDataHeader, HashMap<FirstCategoryCMD, List<SecondCategoryCMD>> listChildData) {
			this.context = context;
			this.listDataHeader = listDataHeader;
			this.listDataChild = listChildData;
		}
		@Override
		public Object getChild(int groupPosition, int childPosititon) {
			return this.listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosititon);
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
			SecondCategoryCMD cmd = (SecondCategoryCMD) getChild(groupPosition, childPosition);
			if (convertView == null) {
				LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = infalInflater.inflate(R.layout.list_second_category_item, null);
			}
			TextView secondCategoryText = (TextView) convertView.findViewById(R.id.secondCategoryText);
			ImageView newImg = (ImageView) convertView.findViewById(R.id.newImg);
			secondCategoryText.setText(cmd.getSecondCategoryText() + " (" + cmd.getProductCount() + ")");
			if (cmd.getNewCount() > 0) {
				newImg.setImageResource(R.drawable.icon_new);
			} else {
				newImg.setImageDrawable(null);
			}
			LinearLayout secondLayout = (LinearLayout) convertView.findViewById(R.id.secondLayout);
			secondLayout.setBackgroundColor(Color.parseColor("#eeffffff"));
			return convertView;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return this.listDataChild.get(this.listDataHeader.get(groupPosition)).size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			return this.listDataHeader.get(groupPosition);
		}

		@Override
		public int getGroupCount() {
			return this.listDataHeader.size();
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
			FirstCategoryCMD cmd = (FirstCategoryCMD) getGroup(groupPosition);
			if (convertView == null) {
				LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = infalInflater.inflate(R.layout.list_first_category_group, null);
			}
			TextView firstCategoryText = (TextView) convertView.findViewById(R.id.firstCategoryText);
			firstCategoryText.setTypeface(null, Typeface.NORMAL);
			firstCategoryText.setText(cmd.getFirstCategoryText());
			
			ImageView noticeTitleImg = (ImageView) convertView.findViewById(R.id.categoryTitleImg);
			//LinearLayout firstLayout = (LinearLayout) convertView.findViewById(R.id.firstLayout);
			
			
			if(isExpanded){
				noticeTitleImg.setImageResource(R.drawable.button_allow_under);
				//firstLayout.setBackgroundColor(Color.parseColor("#eeffffff"));
			} else {
				noticeTitleImg.setImageResource(R.drawable.button_allow);
				//firstLayout.setBackgroundColor(Color.parseColor("#ffffff"));
			}
			
			return convertView;
		}

		@Override
		public boolean hasStableIds() {
			return false;
		}
		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}
    }
	
	public class CategoryWorker extends AsyncTask<Object, FirstCategoryCMD, Object> {
		
		@Override
		protected void onPreExecute() {
			reviewWait.setVisibility(View.VISIBLE);
		}

		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();
				
				/** 읽은 내용을 담기 위한 변수 */
				int idFirstCategory = 0;
				String firstCategoryText = null;
				int idSecondCategory = 0;
				String secondCategoryText = null;
				int productCount = 0;
				int newCount = 0;
				ArrayList<SecondCategoryCMD> second_list = new ArrayList<SecondCategoryCMD>();
				
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("idFirstCategory")) {
							parser.next();
							idFirstCategory = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("firstCategoryText")) {
							parser.next();
							firstCategoryText = parser.getText();
						} else if (tag.equals("idSecondCategory")) {
							parser.next();
							idSecondCategory = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("secondCategoryText")) {
							parser.next();
							secondCategoryText = parser.getText();
						} else if (tag.equals("productCount")) {
							parser.next();
							productCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("newCount")) {
							parser.next();
							newCount = Integer.parseInt(parser.getText().trim());
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("secondCategory_item")) {
							SecondCategoryCMD item = new SecondCategoryCMD(
									idSecondCategory, idFirstCategory, secondCategoryText, null, 0, 0, null, null, productCount, newCount);
							second_list.add(item);
						}
						
						if (tag.equals("item")) {
							FirstCategoryCMD item = new FirstCategoryCMD(idFirstCategory, firstCategoryText, 0, 0, null, null, second_list);
							publishProgress(item);
							second_list = new ArrayList<SecondCategoryCMD>();
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(FirstCategoryCMD... param) {
			listDataHeader.add(param[0]);
			List<SecondCategoryCMD> list = param[0].getSecond_list();
			listDataChild.put(param[0], list);
		}

		@Override
		protected void onPostExecute(Object param) {
			listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
			productCategoryList.setAdapter(listAdapter);
			reviewWait.setVisibility(View.GONE);
		}
		
		@Override
		protected void onCancelled() {
			reviewWait.setVisibility(View.GONE);
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new CategoryWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					getActivity().finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
}
